package handler

import (
	"net/http"
	"strings"
	"os"
	"io/ioutil"
	"fmt"
)

const rootPath = "/list/"

type UserError string

func (err UserError) Error() string {
	return err.Message()
}
func (err UserError) Message() string {
	return string(err)
}

func FileLister(writer http.ResponseWriter, request *http.Request) error {
	path := request.URL.Path
	if index := strings.Index(path, rootPath); index == -1 {
		return UserError(
			fmt.Sprintf("path %s must start with %s", path, rootPath))
	}
	file, e := os.Open(path[len("/list/"):]);
	if e != nil {
		return e
	}
	defer file.Close()
	bytes, e := ioutil.ReadAll(file)
	if e != nil {
		return e
	}
	writer.Write(bytes)
	return nil
}
